package org.jeecg.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.jeecg.modules.entity.DbFinanceManage;
import org.jeecg.modules.mapper.DbFinanceManageMapper;
import org.jeecg.modules.service.IDbContractService;
import org.jeecg.modules.service.IDbFinanceManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @Description: db_finance_manage
 * @Author: jeecg-boot
 * @Date: 2024-07-03
 * @Version: V1.0
 */
@Service
public class DbFinanceManageServiceImpl extends ServiceImpl<DbFinanceManageMapper, DbFinanceManage> implements IDbFinanceManageService {

    @Autowired
    private IDbContractService dbContractService;
    @Override
    @Transactional
    public void updateDbFinanceManage(String contractId, BigDecimal sumCount) {

        QueryWrapper<DbFinanceManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contract_id", contractId);
        DbFinanceManage dm = this.getOne(queryWrapper);
        dm.setReturnedAmount(sumCount);// 回款金额
        BigDecimal rec = dm.getContractAmount().subtract(sumCount);//计算应收
        dm.setReceivableAmount(rec);// 应收金额

        // 修改
        LambdaUpdateWrapper<DbFinanceManage> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(DbFinanceManage::getReturnedAmount, sumCount);
        updateWrapper.set(DbFinanceManage::getReceivableAmount, rec);
        updateWrapper.eq(DbFinanceManage::getId, dm.getId());
        this.update(updateWrapper);

        // 修改合同表回款金额和回款进度
        // 回款比例
        BigDecimal divide = sumCount.divide(dm.getContractAmount(), 4, RoundingMode.HALF_UP);
        float paymentProgress = divide.floatValue()*100; // 百分比
        dbContractService.updateDbContract(contractId, sumCount, paymentProgress);
    }
}
